package controllers

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
	"net/http"
	"sync"
	"user/models"
	"user/utils"
)

type GroupController struct {
	beego.Controller
}

type Connect struct {
	conn *websocket.Conn
	data chan []byte
}

var clientMap = make(map[int]*Connect, 0)

var wg = sync.WaitGroup{}

func (c *GroupController) Group() {
	userid, _ := c.GetInt("user_id")
	groupid, _ := c.GetInt("group_id")

	//token := c.GetString("token")
	//id, t := utils.ParseToken(token)
	//fmt.Println(id)
	//if id != userid && time.Now().Unix() > t {
	//	c.Data["json"] = map[string]interface{}{
	//		"code":    http.StatusCreated,
	//		"message": "请先登录",
	//	}
	//	c.ServeJSON()
	//	return
	//}
	err := models.Ingroup(userid, groupid)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    http.StatusCreated,
			"message": err.Error(),
		}
		c.ServeJSON()
		return
	}
	//存储用户切片
	var member []int
	slice, err := models.GetUser(groupid)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    http.StatusCreated,
			"message": err.Error(),
		}
		c.ServeJSON()
		return
	}
	for _, v := range slice {
		member = append(member, v.UserId)
	}
	conn, err := (&websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
		EnableCompression: false,
	}).Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	n := &Connect{
		conn: conn,
		data: make(chan []byte, 50),
	}
	clientMap[userid] = n
	wg.Add(2)
	go SendMsg(n)
	go RecoverMsg(n, member, userid)
	wg.Wait()
}

func SendMsg(n *Connect) {
	defer wg.Done()
	for {
		select {
		case data := <-n.data:
			err := n.conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				fmt.Println("消息发送失败")
			}
		}
	}
}

func RecoverMsg(n *Connect, member []int, userid int) {
	defer wg.Done()
	for {
		_, msg, err := n.conn.ReadMessage()
		if err != nil {
			fmt.Println("消息接受失败")
		}
		_, err = utils.Ckeck(string(msg))
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		for _, v := range member {
			res, ok := clientMap[v]
			if ok {
				if v != userid {
					res.data <- msg
				} else {
					fmt.Println("不在群里面")
				}
			}
		}
	}
}
